//
//  VideoPlayerView.swift
//  sss
//
//  Created by 顾佳槟 on 2018/3/6.
//  Copyright © 2018年 lancoo. All rights reserved.
//

import UIKit

protocol VideoPlayerViewDelegate: class{
    func resetVideo(imageView:UIImageView,titleLabel:UILabel)
    func updatePorgress(progressBar:UIProgressView)
}

class VideoPlayerView: BaseView {
    
    //音频缩略图
    fileprivate lazy var videoImageView:UIImageView = {
        let _videoImageView = UIImageView.init()
        videoImageViewAnimate(imageView:_videoImageView)
        _videoImageView.layer.pauseAnimation()
        
        return _videoImageView
    }()
    
    //音频标题
    fileprivate lazy var videoTitleLabel:UILabel = {
        let _videoTitleLabel = UILabel.init()
        _videoTitleLabel.textColor = UIColor.black
        _videoTitleLabel.numberOfLines = 0
        _videoTitleLabel.lineBreakMode = .byTruncatingTail
        _videoTitleLabel.font = UIFont.systemFont(ofSize: 18.0)
        
        return _videoTitleLabel
    }()
    
    //音频进度
    fileprivate lazy var progressBar:UIProgressView = {
        let _progressBar = UIProgressView(progressViewStyle:UIProgressViewStyle.default)
        
        _progressBar.progress = 0
        _progressBar.progressTintColor = UIColor.init(hexString: "F86343")
        _progressBar.trackTintColor = UIColor.init(hexString: "B6B5B5")
        
        return _progressBar
    }()
    //播放/暂停按钮
    fileprivate lazy var playButton:UIButton = {
        let _playButton = UIButton.init(type: .custom)
        _playButton.setImage(UIImage.init(named: "VideoPauseIcon"), for: .normal)
        _playButton.addTarget(self, action: #selector(videoPlayButtonClick), for: UIControlEvents.touchUpInside)
        
        return _playButton
    }()
    //下一首按钮
    fileprivate lazy var nextButton:UIButton = {
        let _nextButton = UIButton.init(type: .custom)
        _nextButton.setImage(UIImage.init(named: "VideoPlayNext"), for: .normal)
        _nextButton.addTarget(self, action: #selector(videoNextButonClick), for: UIControlEvents.touchUpInside)
        
        return _nextButton
    }()
    //播放列表按钮
    fileprivate lazy var musicMenuButton:UIButton = {
        let _musicMenuButton = UIButton.init(type: .custom)
        _musicMenuButton.setImage(UIImage.init(named: "VideoMenuIcon"), for: .normal)
        _musicMenuButton.addTarget(self, action: #selector(videoMenuButtonClick), for: UIControlEvents.touchUpInside)

        return _musicMenuButton
    }()
    
    //懒加载音频播放模型
    fileprivate lazy var videoPlayerModel:VideoPlayerModel = {
        let _videoPlayerModel = VideoPlayerModel.init()
        
        return _videoPlayerModel
    }()
    
    //代理
    weak open var delegate: VideoPlayerViewDelegate?
    
    deinit {
        self.videoPlayerModel.removeObserver(self, forKeyPath: "currentPlayMusic")
        self.videoPlayerModel.removeObserver(self, forKeyPath: "currentProgress")
        self.videoPlayerModel.removeObserver(self, forKeyPath: "isPlaying")
    }
    
    override func setupSubviews() {
        
        self.addSubview(self.videoImageView)
        self.videoImageView.mas_makeConstraints({ (make) in
            make?.width.setOffset(65)
            make?.left.setOffset(15)
            make?.top.setOffset(5)
            make?.bottom.setOffset(-5)
        })
        
        self.addSubview(self.progressBar)
        self.progressBar.mas_makeConstraints({ (make) in
            make?.height.setOffset(3)
            make?.top.equalTo()(self)
            make?.left.right().equalTo()(self)
        })
        
        self.addSubview(self.musicMenuButton)
        self.musicMenuButton.mas_makeConstraints({ (make) in
            make?.centerY.equalTo()(self)
            make?.right.setOffset(-15)
            make?.width.height().setOffset(36)
        })
        
        
        self.addSubview(self.nextButton)
        self.nextButton.mas_makeConstraints({ (make) in
            make?.centerY.equalTo()(self)
            make?.right.equalTo()(self.musicMenuButton.mas_left)?.setOffset(-15)
            make?.width.height().setOffset(36)
        })
        
        self.addSubview(self.playButton)
        self.playButton.mas_makeConstraints({ (make) in
            make?.centerY.equalTo()(self)
            make?.right.equalTo()(self.nextButton.mas_left)?.setOffset(-15)
            make?.width.height().setOffset(36)
        })

        
        self.addSubview(self.videoTitleLabel)
        self.videoTitleLabel.mas_makeConstraints({ (make) in
            make?.top.setOffset(10)
            make?.left.equalTo()(self.videoImageView.mas_right)?.setOffset(10)
            make?.right.equalTo()(self.playButton.mas_left)?.setOffset(-20)
            make?.height.setOffset(30)
        })
    }
    
    override func config() {
        self.backgroundColor = UIColor.init(hexString: "F5F5F5")
        
        //绑定属性
        self.videoPlayerModel.addObserver(self, forKeyPath: "currentPlayMusic", options: [.new,.old], context: nil)
        self.videoPlayerModel.addObserver(self, forKeyPath: "currentProgress", options: [.new,.old], context: nil)
        self.videoPlayerModel.addObserver(self, forKeyPath: "isPlaying", options: [.new,.old], context: nil)
        //请求数据
        self.videoPlayerModel.requestData()
        
    }
}

//代理方法
extension VideoPlayerView{
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "currentPlayMusic" {
            self.videoImageView.image = self.videoPlayerModel.currentPlayMusic?.image != nil ? self.videoPlayerModel.currentPlayMusic?.image : UIImage.init(named: "VideoDefaultIcon")
            self.videoTitleLabel.text = self.videoPlayerModel.currentPlayMusic?.videoTitle
        }else if keyPath == "currentProgress"{
            self.progressBar.setProgress((change?[NSKeyValueChangeKey.newKey] as! NSNumber).floatValue, animated: true)
        }else if keyPath == "isPlaying"{
            self.playButton.setImage(UIImage.init(named: self.videoPlayerModel.isPlaying.boolValue ? "VideoPlayIcon" : "VideoPauseIcon"), for: .normal)
            
            if self.videoPlayerModel.isPlaying.boolValue{
                self.videoImageView.layer.resumeAnimation()
            }else
            {
                self.videoImageView.layer.pauseAnimation()
            }
        }
    }
}

extension VideoPlayerView{
    func videoImageViewAnimate(imageView:UIImageView){
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * Double.pi
        anim.duration = 3
        anim.repeatCount = MAXFLOAT
        anim.isRemovedOnCompletion = true
        imageView.layer.add(anim, forKey: nil)
//        videoImageView.layer.removeAllAnimations()
//        UIView.animate(withDuration: 0.2) {
//            self.videoImageView.transform = self.videoImageView.transform.rotated(by: CGFloat(Double.pi))
//        }
    }
}

//控件点击事件
extension VideoPlayerView{
    @objc func videoPlayButtonClick(){
        if self.videoPlayerModel.isPlaying.boolValue {
            self.videoPlayerModel.stop()
        }else{
            self.videoPlayerModel.start()
        }
    }
    
    @objc func videoNextButonClick(){
        self.videoPlayerModel.next()
    }
    
    @objc func videoMenuButtonClick(){
        
    }
}
